var ws, spage, uid, aid;
document.addEventListener('plusready', function(){
	uid = plus.storage.getItem('uid');
	ws = plus.webview.currentWebview();
	spage = ws.spage;
	console.log(spage);
	//查询之前是否有填写过收货地址
	$.ajax({
		type:"get",
		url:apiRoot+"/home/medicinal/address",
		data :{uid:uid},
		dataType :'json',
		success :function(data){
			console.log(JSON.stringify(data));
			if(data != null){
				aid = data.id;
				$('input[name=name]').val(data.name);
				$('input[name=phone]').val(data.phone);
				$('input[name=zipcode]').val(data.zipcode);
				$('input[name=address]').val(data.address);
				$('textarea[name=info]').val(data.info);
			}
		},
		error :function(e){
			console.log(JSON.stringify(e));
			errortoast();
		}
	});
	//点击确认保存收货地址
	$('header span').on('tap', function(){
		var isNull = false;
		$("input, textarea").each(function() {
			var _this = $(this);
			var _val = _this.val();
			if(!_val.trim()) {
				toast('请填写' + _this.siblings('label').text());
				setTimeout(function () {
					_this.focus();
				},50);
				isNull = true;
				return false;
			}else if(_this.attr('type') == 'number'){
				console.log(_this.attr('name'))
				var base;
				switch(_this.attr('name')){
					case 'phone':
						base = p1;
					break;
					case 'zipcode':
						base = re;
					break;
				}
				if(!_val.match(base)){
					toast(_this.siblings('label').text()+'格式不正确');
					setTimeout(function () {
						_this.focus();
					},50);
					isNull = true;
					return false;							
				}
			}
		});
		if(isNull) {
			return;
		}
		var str = $("form[name='editaddress']").serialize();
		var address = $('input[name=address]').val();
		var zipcode = $('input[name=zipcode]').val();
		showWating();
		console.log(JSON.stringify(str));
		console.log(apiRoot+"?m=home&c=medicinal&a=editaddress&"+str+"&uid="+uid+"&address="+address);
		$.ajax({
			type:"get",
			url:apiRoot+"?m=home&c=medicinal&a=editaddress&"+str,
			data :{
				uid :uid,
				address :address
			},
			dataType :'json',
			success :function(data){
				plus.nativeUI.closeWaiting();
				console.log(JSON.stringify(data));
				if(data > 0){
					toast('操作成功');
					if(spage)mui.fire(plus.webview.getWebviewById(spage), 'changeaddress', 
						{name:$('input[name=name]').val(),
						phone:$('input[name=phone]').val(), 
						address:address, 
						zipcode:zipcode, 
						info:$('textarea[name=info]').val()});
					ws.close();
				}else{
					toast('操作失败');
				}
			},
			error :function(e){
				console.log(JSON.stringify(e));
				errortoast();
			}
		});
	})
}, false)